<template>
    <div>
        <!-- 部门管理 -->
        <el-form v-if="showSearch" :model="params">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="部门名称" :class="{ 'bold-label': true }">
                        <el-input v-model="params.deptName" placeholder="请输入部门名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="状态" :class="{ 'bold-label': true }">
                        <el-select clearable v-model="params.status" placeholder="部门状态">
                            <el-option label="正常" value="0" />
                            <el-option label="停用" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-button :icon="Search" type="primary" @click="SearchMaterialType">搜索</el-button>
                    <el-button :icon="Refresh" type="primary" plain @click="paramsReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="primary" :icon="Plus" plain @click=handleaddW>新增</el-button>
                    <el-button type="info" plain :icon="Sort" @click="handleUnfold">展开/折叠</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle @click="toggleSearch" />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle @click="Reload" />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>

        <!-- 表格部分 -->
        <el-row>
            <el-table :data="tableData" row-key="deptId" :default-expand-all="isUnfold"
                :expand-row-keys="expandedRowKeys">
                <el-table-column prop="deptName" label="部门名称" />
                <el-table-column prop="orderNum" label="排序" align="center" />
                <el-table-column prop="status" label="状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '0' ? 'primary' : 'danger'">
                            {{ scope.row.status === '0' ? '正常' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" />
                <el-table-column width="253px" label="操作" align="center">
                    <template #default="scope">
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="EditPen"
                            @click="handleupdate(scope.$index, scope.row)">修改</el-button>
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="Plus"
                            @click="handleadd(scope.$index, scope.row)">新增</el-button>
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="Delete"
                            v-show="scope.row.parentId !== 0"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <!-- 添加弹窗显示 -->
        <el-dialog v-model="dialogVisibleAdd" :title="title" draggable width="50%" @close="handleClose"
            @open="handleOpenCardDialogAdd">
            <el-form :model="deptsAdd" :rules="rulesAdd" ref="ruleFormRefAdd" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级部门" :class="{ 'bold-label': true }" prop="parentId">
                            <el-tree-select v-model="deptsAdd.parentId" :data="treeData" check-strictly
                                node-key="deptId" :props="{ label: 'deptName', children: 'children' }"
                                placeholder="请选择上级部门" :render-after-expand="false" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="部门名称" :class="{ 'bold-label': true }" prop="deptName">
                            <el-input v-model="deptsAdd.deptName" placeholder="请输入分类名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="sort-col">
                        <el-form-item label="显示排序" :class="{ 'bold-label': true }" prop="orderNum">
                            <el-input-number v-model="deptsAdd.orderNum" :min="0" controls-position="right">
                                <template #input>
                                    <span v-if="deptsAdd.orderNum !== 0">{{ deptsAdd.orderNum }}</span>
                                </template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="负责人" :class="{ 'bold-label': true }">
                            <el-input v-model="deptsAdd.leader" placeholder="请输入负责人" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" :class="{ 'bold-label': true }">
                            <el-input v-model="deptsAdd.phone" placeholder="请输入联系电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="邮箱" :class="{ 'bold-label': true }">
                            <el-input v-model="deptsAdd.email" placeholder="请输入邮箱" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="status-col">
                        <el-form-item label="部门状态" :class="{ 'bold-label': true }">
                            <el-radio-group v-model="deptsAdd.status">
                                <el-radio value="0">正常</el-radio>
                                <el-radio value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmitAdd(ruleFormRefAdd)">确定</el-button>
                    <el-button @click="dialogCancel">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改弹窗显示 -->
        <el-dialog v-model="dialogVisibleUpdate" :title="title" draggable width="50%" @close="handleClose"
            @open="handleOpenCardDialogUpdate">
            <el-form :model="deptsUpdate" :rules="rulesUpdate" ref="ruleFormRefUpdate" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级部门" :class="{ 'bold-label': true }" prop="parentId">
                            <el-tree-select v-model="deptsUpdate.parentId" :data="treeData" check-strictly
                                node-key="deptId" :props="{ label: 'deptName', children: 'children' }"
                                placeholder="请选择上级部门" :render-after-expand="false" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="部门名称" :class="{ 'bold-label': true }" prop="deptName">
                            <el-input v-model="deptsUpdate.deptName" placeholder="请输入分类名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="sort-col">
                        <el-form-item label="显示排序" :class="{ 'bold-label': true }" prop="orderNum">
                            <el-input-number v-model="deptsUpdate.orderNum" :min="0" controls-position="right">
                                <template #input>
                                    <span v-if="deptsUpdate.orderNum !== 0">{{ deptsUpdate.orderNum }}</span>
                                </template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="负责人" :class="{ 'bold-label': true }">
                            <el-input v-model="deptsUpdate.leader" placeholder="请输入负责人" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" :class="{ 'bold-label': true }">
                            <el-input v-model="deptsUpdate.phone" placeholder="请输入联系电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="邮箱" :class="{ 'bold-label': true }">
                            <el-input v-model="deptsUpdate.email" placeholder="请输入邮箱" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="status-col">
                        <el-form-item label="部门状态" :class="{ 'bold-label': true }">
                            <el-radio-group v-model="deptsUpdate.status">
                                <el-radio value="0">正常</el-radio>
                                <el-radio value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmitUpdate(ruleFormRefUpdate)">确定</el-button>
                    <el-button @click="dialogCancel">取消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Search, Refresh, Sort, Plus, EditPen, Delete } from '@element-plus/icons-vue'
import { findDeptList, deleteDept, insertDept, updateDept, findBy_deptId } from '@/apis/lth/index'
import { ElMessage, ElMessageBox } from "element-plus";

// 搜索参数
const params = ref({
    deptName: '',
    status: null
})
const tableData = ref([]) // 表格数据
const isUnfold = ref(true) // 默认是否展开
const expandedRowKeys = ref([]) // 存储展开行
const dialogVisibleAdd = ref(false) // 添加弹窗显示
const dialogVisibleUpdate = ref(false) // 修改弹窗显示
const title = ref('') // 弹窗标题
let deptsAdd = ref({
    status: '0'
})
let deptsUpdate = ref({})
let treeData = ref([]);//加载数据

const findDept = () => {
    findDeptList(params.value).then(res => {
        tableData.value = res
    });
}

const findDeptTree = () => {
    findDeptList().then(res => {
        treeData.value = res
    });
}

// 页面加载完成后执行
onMounted(() => {
    findDept();
    findDeptTree();
})
/**
 * 搜索岗位
 */
const SearchMaterialType = async () => {
    if (params.value.status == undefined) {
        params.value.status = null
    }
    try {
        const data = await findDeptList(params.value);
        tableData.value = []; // 清空数据,重新请求数据
        nextTick(() => {
            tableData.value = data;
        });
    } catch (error) {
        console.error('Failed to search dept type:', error);
    }
}
/**
 * 处理 展开/折叠
 */
const handleUnfold = () => {
    if (isUnfold.value) {
        expandedRowKeys.value = []
    } else {
        expandedRowKeys.value = tableData.value
    }
    isUnfold.value = !isUnfold.value
}

//隐藏搜索条件
const showSearch = ref(true);
const toggleSearch = () => {
    showSearch.value = !showSearch.value;
}
//刷新
const Reload = async () => {
    await SearchMaterialType()
}

/**
 * 新增部门，弹窗显示层(无指定添加)
 * @param index 
 * @param row 
 */
const handleaddW = () => {
    title.value = '添加部门'
    dialogVisibleAdd.value = true
}
/**
 * 新增部门，弹窗显示层
 * @param index 
 * @param row 
 */
const handleadd = (index, row) => {
    title.value = '添加部门'
    dialogVisibleAdd.value = true
    deptsAdd.value.parentId = row.deptId
}
const ruleFormRefAdd = ref()
//定义响应式对象，用于重置表单
const resetForm = reactive({ ...deptsAdd })
//验证规则对象
const rulesAdd = {
    parentId: [
        {
            required: true,//必填项
            message: "上级部门不能为空",//提示错误信息
            trigger: "blur"//触发验证的时机，当失去焦点时触发
        }
    ],
    deptName: [
        { required: true, message: "部门名称不能为空", trigger: "blur" }
    ],
    orderNum: [
        { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ]
}
//打开对话框的处理函数
const handleOpenCardDialogAdd = () => {
    nextTick(() => {
        //清空校验（清空表单校验结果，以便用户重新输入数据）
        ruleFormRefAdd.value.clearValidate()
    })
}
/**
 * 添加部门，数据提交
 */
const handleSubmitAdd = async (value) => {
    value.validate(valid => {
        if (valid) {
            insertDept(deptsAdd.value).then(res => {
                if (res == "成功") {
                    dialogVisibleAdd.value = false
                    ElMessage.success(`新增成功`);
                    handleClose();
                } else {
                    ElMessage.error("新增失败");
                }
            })
        } else {
            //ElMessage.error("请根据提示填写完整表单");
        }
    })
}
/**
 * 修改部门，弹窗显示层
 * @param index 行索引
 * @param row 行数据
 */
const handleupdate = (index, row) => {
    title.value = '修改部门';
    dialogVisibleUpdate.value = true;
    Object.assign(deptsUpdate.value, row);// console.log(deptsUpdate.value)
}
const ruleFormRefUpdate = ref()
//定义响应式对象，用于重置表单
const resetFormUpdate = reactive({ ...deptsUpdate })
//验证规则对象
const rulesUpdate = {
    parentId: [
        {
            required: true,//必填项
            message: "上级部门不能为空",//提示错误信息
            trigger: "blur"//触发验证的时机，当失去焦点时触发
        }
    ],
    deptName: [
        { required: true, message: "部门名称不能为空", trigger: "blur" }
    ],
    orderNum: [
        { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ]
}
//打开对话框的处理函数
const handleOpenCardDialogUpdate = () => {
    nextTick(() => {
        //清空校验（清空表单校验结果，以便用户重新输入数据）
        ruleFormRefUpdate.value.clearValidate()
    })
}
/**
 * 修改部门，数据提交
 */
const handleSubmitUpdate = async (value) => {
    value.validate(valid => {
        if (valid) {
            updateDept(deptsUpdate.value).then(res => {
                if (res == "成功") {
                    dialogVisibleUpdate.value = false
                    ElMessage.success(`修改成功`);
                    handleClose();
                } else {
                    ElMessage.error(`修改失败`);
                }
            })
        } else {
            //ElMessage.error("请根据提示填写完整表单");
        }
    })
}
/**
 * 删除部门
 * @param index 行索引
 * @param row 行数据
 */
const ids = ref([]);
const handleDelete = async (index, row) => {
    ids.value.length = 0;
    ids.value.push(row.deptId);
    // console.log("部门ID：",ids.value);
    ElMessageBox.confirm(`是否确认删除名称为${row.deptName}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if (row.children != null) {
            ElMessage.error("存在下级部门，不允许删除");
            return;
        }
        const count = await findBy_deptId(ids.value);
        // console.log("查询到部门条数：",count)
        if (count > 0) {
            ElMessage.error(`部门存在用户，不允许删除`);
            ids.value = [];
            return;
        }
        await deleteDept(ids.value);
        await SearchMaterialType();
        ElMessage.success("删除成功");

    })
}

/**
 * 关闭弹窗,处理数据
 */
const handleClose = async () => {
    await SearchMaterialType()
    resetData();
}
//弹窗取消
const dialogCancel = () => {
    dialogVisibleAdd.value = false
    dialogVisibleUpdate.value = false
    resetData()
}
/**
 * 重置弹窗数据
 */
function resetData() {
    deptsAdd.value = { status: '0' }
    deptsUpdate.value = {}
    title.value = ''
}
/**
 * 重置搜索参数
 */
const paramsReset = async () => {
    params.value = {
        deptName: '',
        status: null
    },
        await SearchMaterialType();
}
</script>

<style scoped>
.dividing-line {
    text-align: center;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}


/* 使用 ::v-deep 选择器 */
::v-deep .el-table .el-table__header-wrapper thead tr th {
    background-color: #f8f8f9 !important;
    /* 你可以根据需要更改颜色 */
    color: #515a6e !important;
    /* 文字颜色 */
}

/* 如果需要更具体的控制，可以使用更详细的类名 */
::v-deep .el-table .el-table__header-wrapper thead tr th,
::v-deep .el-table .el-table__body-wrapper tbody tr td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

/* 使用 ::v-deep 选择器来穿透作用域样式 */
::v-deep .el-table th,
::v-deep .el-table td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

::v-deep .bold-label .el-form-item__label {
    font-weight: bold !important;
}
</style>
